﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CoolERP_BLL;
using CoolERP_Entities;
using System.Web.UI.HtmlControls;
using System.Data;


namespace CoolERP_Web.User
{
    public partial class User_Add : BasePage
    {
        Guid nowDepId = new Guid();//当前部门Id
        Users user = new Users();
        string photoPath = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            nowDepId = Guid.Parse(this.GetUrlParam("id").ToString());//获得当前部门Id
            if (!IsPostBack)
            {
                setControls();
                tbCode.Text = "1" + getNowDepId();
            }
        }

        //获得当前部门的部门编号
        private string getNowDepId()
        {
            DepartmentsBLL depB = new DepartmentsBLL();
            Departments entity = depB.GetEntity(t => t.Id == nowDepId);
            return entity.Code.ToString().Trim();
        }

        private void setControls()
        {
            this.tbBirthday.Attributes.Add("onclick", "show()");
        }

        protected void btnSave_OnClick(object sender, ImageClickEventArgs e)
        {
            GetNewUserInfo();
            Guid temp = nowDepId;
            int sameCodeCount = 0; //工号重复判断
            using (UsersBLL userB = new UsersBLL())
            {
                List<Users> sameCodeList = userB.GetList(t => t.Code.Trim() == user.Code);
                sameCodeCount = sameCodeList.Count;
                if (sameCodeCount == 0)
                {
                    try
                    {
                        userB.Insert(user);
                        using (UserInDepartmentsBLL userInDepB = new UserInDepartmentsBLL())
                        {
                            UserInDepartments entityTemp = new UserInDepartments();
                            entityTemp.UserId = user.Id;
                            entityTemp.DepartmentId = temp;
                            entityTemp.IsManager = 0;
                            userInDepB.Insert(entityTemp);
                        }
                        ShowMessage("新增用户成功！");
                        // Response.Redirect("~/User/Organization.aspx");
                    }
                    catch (Exception ex)
                    {
                        ShowMessage("新增用户失败：" + ex.Message);
                    }
                }
                else
                {
                    ShowMessage("该工号已被使用，请更换一个!");
                    return;
                }
            }

        }

        protected void btnBack_OnClick(object sender, ImageClickEventArgs e)
        {
            //Response.Write("<script language=javascript>history.go(-2);</script>");
            Response.Redirect("~/User/Organization.aspx?id=" + nowDepId.ToString().Trim());
        }

        private void GetNewUserInfo()
        {
            user.Id = Guid.NewGuid();
            user.Code = tbCode.Text.Trim();
            user.ICCard = tbICCard.Text.Trim();
            user.Name = tbName.Text.Trim();
            user.IdNumber = tbIdNumber.Text.Trim();
            user.HomeTown = tbHomeTown.Text.Trim();
            user.Archives = tbArchives.Text.Trim();
            user.Gender = int.Parse(this.rbGender.SelectedValue);
            user.Password = tbPassword.Text.Trim();
            string dtstr = this.tbBirthday.Text.Trim();
            if (!string.IsNullOrEmpty(dtstr))
            {
                user.Birthday = DateTime.Parse(dtstr);
            }
            user.Tel = tbTel.Text.Trim();
            user.Mobile = tbMobile.Text.Trim();
            user.Email = tbEmail0.Text.Trim();
            if (UploadPhotoFile(user.Id))
            {
                lbResult.Text = "照片上传成功";
            }
            else lbResult.Text = "照片上传失败";
            user.Photo = photoPath;
            user.Address = tbAddress.Text.Trim();
        }

        private bool UploadPhotoFile(Guid userId)
        {
            if (PhotoFileUpload.HasFile)
            {
                //判断文件是否小于10Mb   
                if (PhotoFileUpload.PostedFile.ContentLength < 10485760)
                {
                    try
                    {
                        //用当前上传时间给用户照片命名
                        string fileName = DateTime.Now.ToString("yyyyMMddHHmmssffff") + System.IO.Path.GetExtension(PhotoFileUpload.FileName);
                        //判断用户照片目录是否存在
                        string str = Server.MapPath("~/UserPhoto/");
                        if (!System.IO.Directory.Exists(str))
                        {
                            System.IO.Directory.CreateDirectory(str);
                        }

                        int sameCodeCount = 0;
                        using (UsersBLL userB = new UsersBLL())
                        {
                            List<Users> sameCodeList = userB.GetList(t => t.Code.Trim() == user.Code);
                            sameCodeCount = sameCodeList.Count;
                        }
                        if (sameCodeCount == 0)
                        {
                            //上传文件并指定上传目录的路径
                            PhotoFileUpload.PostedFile.SaveAs(str + fileName);
                            photoPath = fileName;
                            return true;
                        }
                        else
                        {
                            //lbResult.Text = "工号重复，不能上传照片";
                            return false;
                        }
                        /*注意->这里为什么不是:FileUpLoad1.PostedFile.FileName  
                        * 而是:FileUpLoad1.FileName?  
                        * 前者是获得客户端完整限定(客户端完整路径)名称  
                        * 后者FileUpLoad1.FileName只获得文件名.  
                        */

                        //当然上传语句也可以这样写(貌似废话):   
                        //FileUpLoad1.SaveAs(@"D:\"+FileUpLoad1.FileName);

                    }
                    catch (Exception ex)
                    {
                        return false;
                        ShowMessage(ex.Message);
                    }

                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }

        }

    }
}